# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

"""
user management
add 
delete
modify
...
"""
import utils.pgsql.base.pgconn as pgconn
import time
import json

_tblName = "tbl_user"

_DB_SCRIPT = """
-- user table ， userId from wechat app 
CREATE TABLE IF NOT EXISTS tbl_user(
                "userId"  VARCHAR(260) PRIMARY KEY ,                
                "appId"   VARCHAR(260) NOT NULL default '',        
                "tenantId" VARCHAR(260) NOT NULL default '',        
                "userName" VARCHAR(260) NOT NULL default '',        
                "nickName" VARCHAR(260) NOT NULL default '',        
                "pwd"  VARCHAR(256) NOT NULL default '',
                "phone" VARCHAR(32) NOT NULL default '',
                "sex" INTEGER NOT NULL default 0, -- 0 man , 1 women
                "imgUrl" VARCHAR(256) NOT NULL default '',          
                "hardId" VARCHAR(256) NOT NULL default '',          
                "attributes" VARCHAR(512) NOT NULL default '',      
                "userIntor" VARCHAR(256) NOT NULL default '',       
                "deliveryAdress" json,                              
                "likeList" json,                              
                "publishList" json,                             
                "collectList" json,                             
                "caseId" INTEGER NOT NULL default 0,         
                "createTime" VARCHAR(32) NOT NULL default '',
                "updateTime" VARCHAR(32) NOT NULL default '',
                "lastLoginTime" VARCHAR(32) NOT NULL default ''     
                );
                
CREATE INDEX IF NOT EXISTS idx_tbl_user_username  ON tbl_user("userName");  
CREATE INDEX IF NOT EXISTS idx_tbl_user_nickname  ON tbl_user("nickName"); 
CREATE INDEX IF NOT EXISTS idx_tbl_user_phone  ON tbl_user("phone");
"""


class PgUser:
    def __init__(self):
        self._pgConn = pgconn.pgMainConn

    def __del__(self):
        pass

    
    def createTbl(self):
        return self._pgConn.exec(_DB_SCRIPT)

    def addUser(self, diXx):
        diXx["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        sql_key = '\"' + '\", \"'.join(diXx.keys()) + '\"'
        sql_val = ''
        for key in diXx:
            if type(diXx[key]) is str:
                sql_val = sql_val + '\'' + diXx[key] + '\','
            else:
                sql_val = sql_val + str(diXx[key]) + ' ,'

  
        sql = "insert into {} ({}) values ({}) ".format(_tblName, sql_key, sql_val[:-1])
        return self._pgConn.exec(sql)

    def updateUser(self, diXx):
        diXx["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
   
        sql_key = '\"' + '\", \"'.join(diXx.keys()) + '\"'
        sql_val = ''
        for key in diXx:
            if type(diXx[key]) is str:
                sql_val = sql_val + '\'' + diXx[key] + '\','
            else:
                sql_val = sql_val + str(diXx[key]) + ' ,'


        sql =  "replace into {} ({}) values ({}) ".format(_tblName, sql_key, sql_val[:-1])
        return self._pgConn.exec(sql)

    def edit(self, diXx, userId):
        diXx["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if "deliveryAdress" in diXx:
            diXx["deliveryAdress"] = json.dumps(diXx["deliveryAdress"])
        if "likeList" in diXx:
            diXx["likeList"] = json.dumps(diXx["likeList"])
        if "publishList" in diXx:
            dic = {}
            dic["publishTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


            sql_key = ''
            for key in dic:
                if type(dic[key]) is str:
                    sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
                else:
                    sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'


            sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])  + " \"ProjectId\" = '{}' ".format(diXx["publishList"][-1])
            
            self._pgConn.exec(sql)

            diXx["publishList"] = json.dumps(diXx["publishList"])
        if "collectList" in diXx:
            diXx["collectList"] = json.dumps(diXx["collectList"])

        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'


        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])  + " \"userId\" = '{}' ".format(
            userId
        )
        return self._pgConn.exec(sql)

    def case(self, userId):
        sql = 'Select "caseId",Count("caseId") As Count  FROM tbl_vlog_record where "userId" = \'{}\' GROUP BY "caseId" '.format(
            userId
        )
        return self._pgConn.exec_fetchall(sql)

    def recordedit(self, diXx, ProjectId):
        if "publishIntor" in diXx:
            diXx["publishIntor"] = json.dumps(diXx["publishIntor"])

        sql_key = ''
        for key in diXx:
            if type(diXx[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + diXx[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(diXx[key]) + ' ,'


        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1]) + " \"ProjectId\" = '{}' ".format(ProjectId)
        return self._pgConn.exec(sql)

    def recordnumedit(self, updataname, num, ProjectId):
        sql = 'update tbl_vlog_record set "{}"="{}"+{} where "ProjectId"=\'{}\''.format(
            updataname, updataname, num, ProjectId
        )
        return self._pgConn.exec(sql)

    def recordget(self, userId):
        sql = """select * from tbl_vlog_record where \"userId\" = \'{}\'  order by "createTime" """.format(
            userId
        )
        return self._pgConn.exec_fetchall(sql)

    def recordedit(self, diXx, recordId):
        # diXx["publishTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        sql_key = ''
        for key in diXx:
            if type(diXx[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + diXx[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(diXx[key]) + ' ,'


        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])  + " \"ProjectId\" = '{}' ".format(recordId)
        return self._pgConn.exec(sql)

 
    def publishget(self, publish) -> list:
        sql = 'select a.*,n."userName","imgUrl" from tbl_vlog_record  a left join tbl_user n on a."userId" = n."userId"  where {} '.format(
            publish
        )
        return self._pgConn.exec_fetchall(sql)

    def publishTime(self) -> list:
        sql = 'select a.*,n."userName","imgUrl" from tbl_vlog_record  a left join tbl_user n on a."userId" = n."userId" where a."publishTime" != \'\' order by  a."publishTime" desc LIMIT 20 '
        return self._pgConn.exec_fetchall(sql)

    def delete(self, ids) -> bool:
        sql = "delete from tbl_vlog_record where \"ProjectId\" = '{}' ".format(ids)
        return self._pgConn.exec(sql)

    def updateLoginTime(self):

        timeStr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        sql = " update {} set \"lastLoginTime\" = '{}'".format(_tblName, timeStr)
        return self._pgConn.exec(sql)

    def getUser(self, userid):
        sql = """select * from {} where \"userId\" = \'{}\' """.format(_tblName, userid)
        return self._pgConn.exec_fetchone(sql)


# pg = PgUser()
# pg.createTbl()
